package com.iteaj.iot.taos;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DefaultTaosSqlManager implements TaosSqlManager, BeanFactoryAware {

    private BeanFactory beanFactory;
    private Map<Class<?>, EntityMetas> entityMetasMap = new ConcurrentHashMap<>(16);

    @Override
    public EntityMetas getSql(Class entityClass) {
        EntityMetas entityMetas = entityMetasMap.get(entityClass);
        if(entityMetas == null) {
            synchronized (this) {
                entityMetas = new EntityMetas(entityClass).resolve();
                if(entityClass == null) {
                    throw new TaosException("["+TaosHandle.class.getSimpleName()+"]对象的返回实体对象必须使用"+STable.class.getSimpleName()+"注解");
                }

                entityMetasMap.put(entityClass, entityMetas);
            }
        }

        return entityMetas;
    }

    @Override
    public SqlContext getSql(Object entity) {
        EntityMetas entityMetas = this.getSql(entity.getClass());
        return new SqlContext(entityMetas, null);
    }

    @Override
    public SqlContext getSql(Class entityClass, List<Object> entities) {
        return null;
    }

    @Override
    public void execute(Object entity, TaosHandle handle) {
        SqlContext sql = this.getSql(entity);
//        JdbcTemplate jdbcTemplate = beanFactory.getBean(handle.jdbcTemplate(entity), JdbcTemplate.class);
//        jdbcTemplate.batchUpdate("", new ArrayList<>());
//        System.out.println(sql);
    }

    public Map<Class<?>, EntityMetas> getEntityMetasMap() {
        return entityMetasMap;
    }

    public void setEntityMetasMap(Map<Class<?>, EntityMetas> entityMetasMap) {
        this.entityMetasMap = entityMetasMap;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}
